<template>
  <div>
    ****************
    <el-upload style="margin:0 10px;display: inline-block;" ref="uploadRef"
               action
               :accept="acceptSuffix"
               :on-change="handleChange"
               :limit="1"
               size="small"  class="inline-block"
               :http-request="payStandardUpload"
    >
      <el-button type="primary" size="small" icon="el-icon-upload2"> 导入标准明细</el-button>
    </el-upload>

    <h4>svg图标</h4>
    <img src="../../assets/icons.svg">

    <el-button @click="trigger">this指向</el-button>

    <avue-input-tree
        :data="treeData"
        :props="defaultProps"
        :tree-load="loadTreeData"
    ></avue-input-tree>

    <el-button type="primary" plain @click="sendReq">向后台发请求</el-button>


    vuex store 中的数据：{{$store.state.num}} - {{storeNum}}

    <el-button type="primary" @click="openWindow">打开新窗口</el-button>
    <div style="width: 100%;height: 50vh">
      <iframe :src="`http://${url}/#/searchElTable`" border="none" height="100%" width="100%"></iframe>
    </div>

    <hr-upload :origin-file-list="[{attachmentName:'文件1',attachmentSize:'20K',creatorName:'张三',createTime:'2024-04-05'}]"></hr-upload>

    <div id="target" style="height: 400px;">

    </div>
  </div>
</template>

<script>
import axios from "axios";
import {mapGetters} from 'vuex'
import {menus} from '../../components/hrvue/constant'

export default{
  name:"avue-index",
  computed:{
    ...mapGetters(['storeNum'])
  },
  mounted() {
// MutationObserver 接口提供了监视对 DOM 树所做更改的能力。
    let target = document.getElementById('target');
    function observe() {
      let observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          console.log("********:",mutation, mutation.type);
          // mutation 是一个对象，包含：变化类型、旧值、目标元素等信息
        });
      });
      observer.observe(target, {
        attributes: true, // 布尔值，默认为 false。设置为 true 时，表示观察目标节点的属性变化。
        childList: true, //布尔值，默认为 false。设置为 true 时，表示观察目标节点的子节点列表的变化，包括添加或删除子节点。
        characterData: true, // 布尔值，默认为 false。设置为 true 时，表示观察目标节点文本内容的变化
        subtree: true,// 布尔值，默认为 false。设置为 true 时，表示观察目标节点以及其所有后代节点的变化。
        attributeOldValue: true,// 布尔值，默认为 false。如果设置为 true，则在回调函数的 MutationRecord 对象中包含被修改属性的旧值。
      });
    }
    observe()

    setTimeout(() => {
      target.style.height = '100px'
      target.style.backgroundColor = '#f2f2f2'
    }, 2000)


    console.log("父组件 window.parent：",window.parent == window)

  },
  data() {
    return {
      standardID:"1111",
      systemCode:"2222",
      maxFileSize:10,
      acceptSuffix: ".xlsx,.XLSX",

      defaultProps: {
        label: 'label',
        children: 'children'
      },
      treeData: [],
      url: window.location.hostname + ':' + window.location.port
    }
  },
  created() {

    console.log("*********：",window.location.hostname , window.location.port)

    let codeStr = 0 ;
    const code = +codeStr
    //console.log("code:",typeof code)

   let data = this.transformToMapFormat([{id:1,name:'测试',children:[{id:11,name:'测试11'}]}],'id')
    //console.log("data:",data)

    let ls = this.omit({path:'/',name:'导航',meta:{useGard:false}},["name"]) ;
    //console.log("ls:",ls)


    let useGuard =  ['attendance-attendanceDataMonitorSelf'] ;

   let flag =  useGuard.some(
        (u) => {
          //console.log("u:",u)
         return !!menus[u]
        }
    )

    //console.log("flag:",flag)

    //console.log("document.clientHeight:",document.documentElement.clientHeight)

    window.addEventListener('resize', function() {
      //console.log('窗口大小已变化');
      // 在这里添加你需要执行的代码
      // 例如，可以获取窗口的新尺寸：
      //console.log('宽度:', window.innerWidth);
     // console.log('高度:', window.innerHeight);
     // console.log('高度document.documentElement.clientHeight:', document.documentElement.clientHeight);
    });

      document.cookie = 'JSESSIONID=824B925CCD721892D16DEF12F598D25C;'
      document.cookie = 'HRD_ID=6f367436e28946c4a86da3f787e5cc41;'
      document.cookie = 'OSP_SID=B095A3DC5CBF4E79B7C8C4633E4332CB;'
      console.log("document.cookie:",document.cookie)


      console.log("JSESSIONID:",this.getCookie('JSESSIONID'))
      console.log("HRD_ID:",this.getCookie('HRD_ID'))
      console.log("OSP_SID:",this.getCookie('OSP_SID'))

  },
  methods:{
    getCookie(name) {
      let matches = document.cookie.match(new RegExp(
          "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    } ,
    sendReq(){
    document.cookie = "username=John; path=/example";
    // console.log("document.cookie:",document.cookie)
     const instance = axios.create({
        baseURL:'',
        timeout:1000
      })
      instance.defaults.withCredentials = true ;
      instance.get('/use',{
        params:{
          ID:12334
        }
      })
    },
    loadTreeData(node, resolve) {
      // console.log("*******************")
      // 模拟异步加载数据
      setTimeout(() => {
        // 假设根节点是pid为0的节点
        const data = [
          { id: 1, label: '子节点1', pid: node.data.id },
          { id: 2, label: '子节点2', pid: node.data.id }
        ];
        // 调用resolve传入子节点数据
        resolve(data);
      }, 1000);
    },
    trigger(){

    },
    handleChange(file, fileList) {

      // console.log("***********file:",file)

      if (file.status !== "ready") {//只处理选择文件，在上传成功或失败调用时不做任何处理
        return true
      }
      //console.log("file", file)
      //console.log("fileList", fileList)
      if (file.name.indexOf(".") === -1) {
        this.$message({
          message: '上传文件没有扩展名，无法识别!',
          type: 'warning'
        });
        this.removeFileFromList(file, fileList)
        return false
      }
      let nameEnd = file.name.substring(file.name.lastIndexOf('.') + 1)
      let picEnd = this.$refs['upload'].accept.replace(/\./g, "")


      if ((',' + picEnd + ',').indexOf("," + nameEnd + ",") === -1) {
        this.$message({
          message: '上传文件只能是' + picEnd + '格式其中一种!',
          type: 'warning'
        });
        this.removeFileFromList(file, fileList)
        return false
      }
      let isLt = file.size / 1024 / 1024 < this.maxFileSize
      if (!isLt) {
        this.$message({
          message: '上传文件大小不能超过' + this.maxFileSize + 'MB!',
          type: 'warning'
        });
        this.removeFileFromList(file, fileList)
        return false
      }
      return true
    },
    removeFileFromList(file, fileList) {
      let index = fileList.findIndex(item => item.name === file.name)
      fileList.splice(index, 1);
    },
    payStandardUpload(fileInfo){
      //console.log("&&&&:",this.$refs.uploadRef.fileList)

    let object = this.upload('http://localhost:8080/upload/'+this.standardID + this.systemCode,
        fileInfo.file,
        {
            standardID:this.standardID,
            systemCode:this.systemCode
          },
         undefined,
        {
          params:{
            name:'小明',
            age:18
          }
        }

        )
      // console.log("object:",object.data)

      let formData = object.data ;
      // 使用for...of循环遍历FormData中的所有属性

      let data = {} ;
      formData.forEach((value, key) => data[key] = value);
      // console.log("****",data);

    },
    upload(url, files, data = {}, field = 'file', option = {}) {
      if (typeof url === 'object') {
        data = url.data || {}
        option = this.omit(url, ['data'])
        //console.log("option:",option)
      }
      if (typeof url === 'string') {
        option = { url, ...option }
      }
      const fd = new FormData()
      if (Array.isArray(files)) {
        files.forEach((raw) => {
          fd.append(field, raw)
        })
      } else {

        fd.append(field, files)
      }
      Object.keys(data).forEach((key) => {
        fd.append(key, data[key])
      })

      return {
        ...option,
        data:fd
      }
      // return fetch({
      //   ...option,
      //   method: 'POST',
      //   data: fd,
      //   headers: { 'content-type': 'multipart/form-data' }
      // })
    },
    isNull(val){return val === null} ,
    omit(obj, fields, truthy = false, deleteBlank = false) {
      const shallowCopy = { ...obj }
      if (truthy) {
        Object.keys(obj).forEach((key) => {
          if (this.isNull(obj[key]) || Number.isNaN(obj[key]) || obj[key] === undefined || (deleteBlank && obj[key] === '')) {
            fields.push(key)
          }
        })
      }

      for (let i = 0; i < fields.length; i++) {
        const key = fields[i]
        delete shallowCopy[key]
      }

      return shallowCopy
    },
// 嵌套的树形数据转为平铺数据
  transformToMapFormat (nodes = [], field, level = 0, data = null, parent = null){
      data = data || {}
      let l = level
      nodes.forEach((r, i) => {
        if (parent) {
          const ancestors = parent.parent || []
          delete parent.children
          // delete parent.parent
          r.parent = [...ancestors, parent]
        }
        if (r.children) {
          l++
          this.transformToMapFormat(r.children, field, ++l, data, { ...r })
        }
        delete r.children
        r.__index__ = level
        if (!data[r[field]]) {
          data[r[field]] = r
          return
        }
        data[r[field]].otherParentIds = data[r[field]].otherParentIds || []
        if (parent) {
          data[r[field]].otherParentIds.push(parent.guid)
        }
      })
      return data
    },
    openWindow(){
      window.open('https://baidu.com','_blank')
    }

  }
}
</script>